package com.kg.sdk.util;

import android.os.Handler;
import android.widget.TimePicker;

/**
 * Created by Administrator on 2018-11-25.
 */

public class CommonTimer {
    private Handler mHandler;
    private int mTime = 0;
    private Runnable mRunner;
    private int perTime = 1000;
    private boolean isStart = false;
    private OnTimeChangedListener mTimeChangedListener;
    public CommonTimer(){
        mHandler = new Handler();
        initRunner();
    }

    private void initRunner(){
        mRunner = new Runnable() {
            @Override
            public void run() {
                if(isStart){
                    mHandler.postDelayed(this, perTime);
                    mTime++;
                    if(mTimeChangedListener != null){
                        mTimeChangedListener.timeChange(mTime);
                    }
                }

            }
        };
    }

    public void startTime(){
        if(isStart){
            return;
        }
        isStart = true;
        if(mRunner != null){
            mHandler.removeCallbacks(mRunner);
        }
        mTime = 0;
        mHandler.postDelayed(mRunner,perTime);
    }

    public void stopTime(){
        if(!isStart){
            return;
        }
        isStart = false;
        mTime = 0;
        if(mRunner != null){
            mHandler.removeCallbacks(mRunner);
        }
    }

    public void setOnTimeChange(OnTimeChangedListener listener){
        mTimeChangedListener = listener;
    }
    public interface OnTimeChangedListener{
        void timeChange(int time);
    }
}

